package com.jokins.admin.vue.gitlog.action;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jokins.admin.vue.gitlog.actioncontext.GetApplyListDoc;
import com.jokins.admin.vue.gitlog.mapper.ApplyMapper;
import com.jokins.admin.vue.gitlog.param.ApplyParam;
import com.jokins.admin.vue.gitlog.vo.ApplyVo;
import com.jokins.common.actions.action.ActionContext;
import com.jokins.common.actions.action.BaseAction;
import com.jokins.common.actions.exception.BusinessException;
import com.jokins.common.entry.vue.gitlog.Apply;
import com.jokins.common.util.SqlTypeConverter;
import com.jokins.common.util.date.DateFormatter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Component
public class GetApplyListDocAction extends BaseAction<GetApplyListDoc> {

    @Autowired
    private ApplyMapper applyMapper;

    @Override
    protected void process(GetApplyListDoc actionContext) throws BusinessException {
        ApplyParam param = actionContext.getParam();
        log.info("进入GetApplyListDocAction。。。。。");
        String applyName = param.getApplyName();
        log.info("Executing GetApplyList SQL query...");
        QueryWrapper<Apply> queryWrapper = new QueryWrapper<>();
        Optional.ofNullable(applyName)
                .filter(name -> !name.isEmpty())
                .ifPresent(name -> queryWrapper.eq("apply_name", name));
        List<Apply> applyList = applyMapper.selectList(queryWrapper);
        List<ApplyVo> applyVoList = applyList.stream()
                .map(apply -> {
                    ApplyVo vo = new ApplyVo();
                    SqlTypeConverter.convertEntity(apply, vo, DateFormatter.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS);
                    return vo;
                })
                .collect(Collectors.toList());
        log.info("Fetched apply: {}", applyVoList);
        log.info("applyVoList:{}", JSON.toJSONString(applyVoList));
        actionContext.setResult(ActionContext.RESULT_DOC_KEY, applyVoList);
    }
}
